#!/bin/sh

# Config
: "${REPOPTH:="https://github.com/fink/fink-distributions.git"}"
FIROOT="/Volumes/src2/fink/selfupdate"
LOCKFILE="/var/run/fink-info-git.lock"

usage() {
	cat > "/dev/stderr" << EOF
usage: ${0} [-l lockfile] [-o outputdir]
Defaults:
	Output: ${FIROOT}
	Lockfile: ${LOCKFILE}
EOF
	exit 1
}

while getopts ":l:o:" OPTION; do
	case "${OPTION}" in
		l)
			LOCKFILE="${OPTARG}"
		;;
		o)
			FIROOT="${OPTARG}"
		;;
		?)
			usage
		;;
	esac
done

# Prevent more than one concurrent update
lockfile -r "0" -l "28800" "${LOCKFILE}" || exit 0

# Make the directories if they do not already exist
if [ ! -d "${FIROOT}/finkinfo" ]; then
	mkdir -p "${FIROOT}/finkinfo"
fi

cd "${FIROOT}"

# Note the start time of a new fetch
date -u +%s > "${FIROOT}/finkinfo/UPDATE"

# Check to see if the initial clone has been made
if [ ! -d "${FIROOT}/finkinfo.tmp/.git" ]; then
	if [ -d "${FIROOT}/finkinfo.tmp" ]; then
		rm -fr "${FIROOT}/finkinfo.tmp"
	fi
	if ! git clone "${REPOPTH}" finkinfo.tmp; then
		echo "clone did not succeed, aborting." >&2
		rm -fr "${LOCKFILE}" "${FIROOT}/finkinfo.tmp"
		exit 1
	fi
fi

# Enter the git repo
cd "${FIROOT}/finkinfo.tmp"

if ! git fetch origin; then
	# We are depending on git to self recover, if it does not, you likely have deeper issues.
	echo "fetch did not succeed, aborting." >&2
	rm -f "${LOCKFILE}"
	exit 1
fi
# Be sure we are on the right branch and then update.
git checkout -f master
if [ "$(git rev-parse master)" = "$(git rev-parse origin/master)" ]; then
	# If we do not need to update the we are done.
	date -u +%s > "${FIROOT}/finkinfo/LOCAL"
	rm -f "${LOCKFILE}"
	exit 0
fi
git reset --hard origin/master

# Exit the git repo
cd "${FIROOT}"

# Make a clean copy out of the git repo
if ! rsync -aq --delete-after --exclude="LOCAL" --exclude="UPDATE" --exclude=".cvsignore" --exclude=".gitignore" --exclude=".git" --exclude=".DS_Store" "${FIROOT}/finkinfo.tmp/" "${FIROOT}/finkinfo/"; then
	rm -f "${LOCKFILE}"
	exit 1
fi

# Add the timestamp
date -u +%s | tee "${FIROOT}/finkinfo/TIMESTAMP" > "${FIROOT}/finkinfo/LOCAL"

# Clean up
rm -f "${LOCKFILE}"

exit 0
